<template>
  <BasicModal centered destroyOnClose
              v-bind="$attrs"
              :width="665"
              :bodyStyle="{overflowY:'hidden', height:'530px'}"
              :title="title"
              :canFullscreen="false"
              :maskClosable="false"
              @ok="handleOk"
              @register="registerModal"
  >
    <a-row type="flex" :gutter="5" style=" margin: 0; padding: 0">
      <a-col flex="240px" style="border: 1px #ddd solid; padding-top: 5px">
        <CooperatorTree @onClick="onClick"/>
      </a-col>
      <a-col flex="400px" style="border: 1px #ddd solid; padding-top: 10px; margin-left: 5px">
        <a-form ref="registerForm" :model="model" :rules="validatorRules" :labelCol="{ span: 6 }" :wrapperCol="{ span: 17 }">
          <a-form-item name="parentId" label="上级" v-show="items.type_kh || items.type_lxr">
            <a-input type="hidden" id="cooperator_id" name="id" v-model:value="model.id" />
            <a-input type="hidden" id="cooperator_type" name="type" v-model:value="model.type" />
            <a-input type="hidden" class="formText" style="width:60px" v-model:value="model.parentId" />
            <a-input readonly class="formText" v-model:value="model.parentAreaName" />
          </a-form-item>
          <a-form-item name="areaName" :label="items.customerText" v-show="items.type_cs || items.type_kh || items.type_lxr">
            <a-input type="text" class="formText " v-model:value="model.areaName" />
          </a-form-item>
          <a-form-item label="排序">
            <a-input-number class="w-150px" v-model:value="model.sort" :min="0" :max="99999" />
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
  </BasicModal>
</template>

<script lang="ts" setup>
import { computed, inject, nextTick, reactive, ref, unref, watch, watchEffect } from "vue";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { cooperatorSave, getCooperatorById } from "../api";
import { RuleObject, ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import CooperatorTree from "./CooperatorTree.vue"
import moment from 'dayjs'

const emit = defineEmits(["success", "register"]);
//接收表单对象
const registerForm = ref();
//表单控件
const items = reactive({
  type_cs: false,
  type_kh: false,
  type_lxr: true,
  customerText: "名称",
  action:'',
});
//表单数据
let model = reactive<any>({});

//是否为更新操作
const isUpdate = ref<boolean>(false);
const title = computed(() => isUpdate.value ? "编辑" : "新增");
//数据类型，默认值
let indexRegisterType = ref<string>('1');

//自定义
let validateLxdh = async (rule: RuleObject, value: string) => {
  if (model.type === '2' && value == '') {
    return Promise.reject('不能为空!');
  } else {
    return Promise.resolve();
  }
};
//表单校验
const validatorRules = {
  type: [{ required: true, message: "不能为空!" }],
  parentId: [{ required: true, message: "不能为空!" }],
  areaName: [{ required: true, message: "不能为空!" }],
  lxr: [{ required: false, message: "不能为空!" }],
  lxdh: [{ required: false, validator: validateLxdh, trigger: 'blue' }]
};

/**
 * 定义组件变量
 */
const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
  setModalProps({ confirmLoading: false });
  resetFields()
  isUpdate.value = !!data?.isUpdate;
  let typeVal = 1;
  if (unref(isUpdate)) {
    //获取详情
    await getCooperatorById({ id: data.record.id }).then((res) => {
      let name = res.pathName.split("|")
      res.parentAreaName = name[name.length - 2] || ''

      //表单赋值
      Object.assign(model, res);
      typeVal  = Number(model.type)
    });
  }
  changeType(typeVal)

});

//表单重置
function resetFields() {
  model.id = null;
  model.type = '';
  model.parentId = '';
  model.parentAreaName = '';
  model.areaName = '';
  model.dwmc = '';
  model.lxr = '';
  model.lxdh = '';
  model.yhhm = '';
  model.khx = '';
  model.lxdh = '';
  model.sort = '';
}

watchEffect(() => {
  model.areaName && initCharts();
});

function initCharts() {
  model.areaName = model.areaName.replace("|","/").replace("｜","/")
  console.info("model.areaName", model.areaName)
}

// 提交事件 registerForm.value.
//const registerForm = ref();
async function handleOk() {
  await registerForm.value.validate().then(async () => {
    try {
      setModalProps({ confirmLoading: true });
      //提交表单
      await cooperatorSave(items.action, model);
      closeModal();
      emit("success");
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }).catch((error: ValidateErrorEntity<any>) => {
    console.log("error", error);
  });
}

/**
 * 树节点点击事件
 * 当点城市 type = 0, 加1后 customer.type = 1 公司
 * @param treeNode
 * @returns {boolean}
 */
function onClick(treeNode) {
  var id = model.id;
  var dataVal = (Number(model.type) + 1);
  var typeVal = (Number(treeNode.type) + 1);     //点选节点属性
  //id有值时为更新，无时为添加
  if (id) {
    if (!dataVal) {
      console.info("dataVal = " + dataVal + ", 数据不符合规范，请检查。");
      return false;
    }
    //当前是地区  dataVal=1，上级目录不可变更
    //当前是公司  dataVal=2，上级目录只可变更到，地区下
    //当前是联系  dataVal=3，上级目录只可变更到，公司下
    //点选的要小于编辑的
    if (dataVal == 1 || (dataVal != (typeVal + 1))) {
      return false;
    }
  } else {

  }

  if (typeVal != undefined && typeVal != null && typeVal >= 0) {
    if (typeVal == 0) {
      // 添加城市
      model.type = typeVal;
      model.parentId = "";
      model.parentAreaName = "";
      changeType(typeVal);
    } else if (typeVal == 1) {
      // 添加公司
      model.type = typeVal;
      model.parentId = treeNode.id;
      model.parentAreaName = treeNode.name;
      changeType(typeVal);
    } else if (typeVal == 2) {
      // 添加联系人
      model.type = typeVal;
      model.parentId = treeNode.id;
      model.parentAreaName = treeNode.name;
      changeType(typeVal);
    } else if (typeVal == 3) {
      model.parentId = "";
      model.parentAreaName = "";
      model.areaName = "";
      model.lxdh = "";
      model.qq = "";
    }
  }
}

function changeType(typeVal: number) {
  //alert($("#searchBoxx").val());
  model.type = typeVal;
  indexRegisterType.value = typeVal + ""
  //$("#searchBoxx").attr("disabled",true);
  if (typeVal == 0) {
    validatorRules.type[0].required = false;
    validatorRules.parentId[0].required = false;
    validatorRules.lxr[0].required = false;
    validatorRules.lxdh[0].required = false;
    items.type_kh  = false;
    items.type_lxr = false;
    items.type_cs  = true;
    items.action = "/cooperator/saveCity";
  } else if (typeVal == 1) {
    validatorRules.type[0].required = true;
    validatorRules.parentId[0].required = true;
    validatorRules.lxr[0].required = false;
    validatorRules.lxdh[0].required = false;
    items.type_cs  = false;
    items.type_lxr = false;
    items.type_kh  = true;
    items.action = "/cooperator/saveDirectory";
  } else if (typeVal == 2) {
    validatorRules.type[0].required = true;
    validatorRules.parentId[0].required = true;
    validatorRules.lxr[0].required = true;
    validatorRules.lxdh[0].required = true;
    items.type_cs  = false;
    items.type_kh  = false;
    items.type_lxr = true;
    items.action = "/cooperator/save";
  }

}

//@change="changeRegisterType"
function changeRegisterType(e) {
  indexRegisterType.value = e.target.value;
  changeType(Number(indexRegisterType.value));
}

</script>

<style scoped lang="less">

.jeecg-basic-tree {
  border: 1px green solid;
  overflow: auto;

  ::v-deep(.ant-tree) {
    li {
      padding: 0 !important;
    }
  }
}

</style>
